define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'applyform/apply/index',
                    add_url: 'applyform/apply/add',
                    edit_url: 'applyform/apply/edit',
                    multi_url: 'applyform/apply/multi',
                    del_url: 'applyform/apply/del',
                    table: 'apply_form',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                queryParams: function (params) {
                    params.rel_type = Config.relType;
                    params.rel_id = Config.relId;

                    // 添加城市和学校参数
                    var cityId = $('#c-cityarea_id').val();
                    var schoolId = $('#c-school_id').val();

                    if (cityId) {
                        params.city_id = cityId;
                    }
                    if (schoolId) {
                        params.school_id = schoolId;
                    }
                    return params;
                },
                escape: false,
                pk: 'id',
                sortName: 'weigh desc,id desc', //要使排序生效，在前面添加 weigh desc, 并且数据表weigh字段不能全为0,controller里$list=...->order前再添加->order("weigh desc")
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id') },
                        { field: "city_id", title: "城市" },
                        { field: 'school_id', title: '学校' },
                        { field: 'apply_type', title: '报名类型' },
                        { field: 'title', title: '报名项目名称' },
                        { field: 'cover', title: '封面 ', formatter: Table.api.formatter.image },
                        { field: 'amount', title: '学费 ' },
                        { field: 'start_time', title: '开始时间', formatter: Table.api.formatter.datetime },
                        { field: 'end_time', title: '结束时间 ', formatter: Table.api.formatter.datetime },
                        { field: 'max_num', title: '招生人数' },
                        { field: 'is_real', title: '是否正式报名' },
                        { field: 'status', title: '状态', formatter: Controller.api.formatter.status },
                        { field: 'is_close', title: '是否关闭' },
                        { field: 'is_finished', title: '是否结束 ' },
                        { field: 'is_end', title: '是否截止' },
                        { field: 'dead_time', title: '截止时间 ', formatter: Table.api.formatter.datetime },
                        {
                            field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                // {
                                //     name: 'detail',
                                //     classname: 'btn btn-xs btn-primary btn-click',
                                //     icon: 'fa fa-sitemap',
                                //     click: function (value, row, index) {
                                //         Backend.api.open('/adminht.php/dept/dept?relType=school&relId='+row.id+'&ref=addtabs', '组织结构2', {
                                //             max: true,
                                //             area: ['80%', '80%'],
                                //             //offset: ['0px', '0px'],
                                //             callback: function (data) {
                                //                 Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                //             }
                                //         });
                                //     }
                                // }
                            ]
                        }
                    ]
                ]
            });
            // 移除自动刷新页面的行为
            // $(document).on('fa.event.success', function(event, data) {
            //     setTimeout(function() {
            //         location.reload();
            //     }, 1000);
            // });

            // 操作指引面板功能
            $(document).on('click', '#toggleGuide', function () {
                var content = $('#guideContent');
                var icon = $(this).find('i');

                if (content.is(':visible')) {
                    content.slideUp(300);
                    icon.removeClass('fa-chevron-up').addClass('fa-chevron-down');
                    $(this).html('<i class="fa fa-chevron-down"></i> 展开');
                } else {
                    content.slideDown(300);
                    icon.removeClass('fa-chevron-down').addClass('fa-chevron-up');
                    $(this).html('<i class="fa fa-chevron-up"></i> 收起');
                }
            });

            // 响应式处理
            function handleResize() {
                if ($(window).width() < 768) {
                    $('.steps-container .row').removeClass('row');
                    $('.steps-container .col-md-6').removeClass('col-md-6').addClass('col-xs-12');
                } else {
                    $('.steps-container > div').addClass('row');
                    $('.steps-container .col-xs-12').removeClass('col-xs-12').addClass('col-md-6');
                }
            }

            handleResize();
            $(window).resize(handleResize);

            // 步骤按钮悬停效果
            $('.step-item button').hover(
                function () {
                    $(this).css('transform', 'scale(1.05)');
                },
                function () {
                    $(this).css('transform', 'scale(1)');
                }
            );
            $(document).ready(function () {
                var urlParams = new URLSearchParams(window.location.search);
                var infoStep = urlParams.get('infostep');

                if (infoStep === '10') {
                    // 设置第8步为完成状态，样式与第7步统一
                    $('.step-item').eq(7).removeClass('current pending').addClass('completed')
                        .css({
                            'background': 'rgba(255,255,255,0.1)',
                            'border-left': '4px solid #28a745',
                            'opacity': '1'
                        });

                    // 更新第8步的标题颜色和按钮
                    $('.step-item').eq(7).find('h6').css('color', '#00ff88');
                    $('.step-item').eq(7).find('button').removeClass('btn-warning').addClass('btn-success').text('已完成');

                    // 设置第9步为完成状态，样式与第7步统一
                    $('.step-item').eq(8).removeClass('current pending').addClass('completed')
                        .css({
                            'background': 'rgba(255,255,255,0.1)',
                            'border-left': '4px solid #00ff88',
                            'opacity': '1'
                        });

                    // 更新第9步的标题颜色和按钮
                    $('.step-item').eq(8).find('h6').css('color', '#00ff88');
                    $('.step-item').eq(8).find('button').removeClass('btn-warning').addClass('btn-success').text('已完成');

                    // 设置第10步为当前步骤
                    $('.step-item').eq(9).removeClass('pending').addClass('current')
                        .css({
                            'background': 'rgba(255,255,255,0.2)',
                            'border-left': '4px solid #ffd700',
                            'box-shadow': '0 2px 8px rgba(255,215,0,0.3)',
                            'opacity': '1'
                        });

                    // 更新第10步的内容和标题颜色
                    $('.step-item').eq(9).find('.step-number').text('5');
                    $('.step-item').eq(9).find('strong').text('项目信息统计');
                    $('.step-item').eq(9).find('p').text('您可以在此处查看平台数据的各种统计信息');
                    $('.step-item').eq(9).find('h6').css('color', '#ffd700'); // 设置第10步标题为黄色
                    $('.step-item').eq(9).find('button').text('管理报名信息').attr('onclick', "window.top.location.href='/applyform/apply/edit'");

                    // 更新进度条为100%
                    $('.progress-bar').css('width', '100%');
                    $('.progress-container span:last-child').text('100% 完成');

                    // 更新步骤显示为第10步
                    $('.operation-guide-panel .row .col-md-8 div:last-child').text('进度：10/10');
                    $('#step').text('第5步 - 项目信息统计');

                    // 更新操作提示内容
                    $('.operation-tips ul').html('<li>在这里可以查看各种课程项目的数据统计</li>');

                }

            });
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/index.js';
            document.head.appendChild(script);
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);
            // 添加报名类型切换事件处理
            $(document).on('change', 'input[name="row[apply_type]"]', function () {
                var applyType = $(this).val();
                if (applyType == '1') {
                    // 显示课程类型字段
                    $('#course-type-group').show();
                } else {
                    // 隐藏课程类型字段
                    $('#course-type-group').hide();
                    // 清空课程类型选择
                    $('input[name="row[course_type]"]').prop('checked', false);
                }
            });

            // 添加分阶段switcher事件处理
            $(document).on('change', '#c-is_staged', function () {
                var isEnabled = $(this).val() == '1';
                if (isEnabled) {
                    // 显示阶段名称输入框
                    $('#staged-names').show();
                    // 显示分阶段报名信息
                    $('#staged-registration-info').show();
                } else {
                    // 隐藏阶段名称输入框
                    $('#staged-names').hide();
                    // 隐藏分阶段报名信息
                    $('#staged-registration-info').hide();
                    // 清空阶段名称输入框的值
                    $('#c-staged_name').val('');
                    // 清空分阶段表单中的所有输入值
                    $('#staged-registration-info input, #staged-registration-info select').val('');
                }
            });

            // 添加报名数量限制switcher事件处理
            $(document).on('change', '#c-enable_quantity_limit', function () {
                var isEnabled = $(this).val() == '1';
                if (isEnabled) {
                    $('#quantity-limit-settings').show();
                } else {
                    $('#quantity-limit-settings').hide();
                    // 清空相关字段
                    $('#quantity-limit-settings input').val('');
                }
            });

            // 添加报名表开启switcher事件处理
            $(document).on('change', '#c-enable_registration_form', function () {
                var isEnabled = $(this).val() == '1';
                if (isEnabled) {
                    $('#registration-form-settings').show();
                } else {
                    $('#registration-form-settings').hide();
                    // 清空相关字段
                    $('#registration-form-settings input, #registration-form-settings textarea').val('');
                    $('#registration-form-settings input[type="checkbox"]').prop('checked', false);
                }
            });

            // 添加手签板switcher事件处理
            $(document).on('change', '#c-enable_signature_pad', function () {
                var isEnabled = $(this).val() == '1';
                if (isEnabled) {
                    $('#signature-pad-settings').show();
                } else {
                    $('#signature-pad-settings').hide();
                    // 清空相关字段
                    $('#signature-pad-settings input, #signature-pad-settings select').val('');
                }
            });

            // 添加事项设置switcher事件处理
            $(document).on('change', '#c-enable_matters_setting', function () {
                var isEnabled = $(this).val() == '1';
                if (isEnabled) {
                    $('#matters-settings').show();
                } else {
                    $('#matters-settings').hide();
                    // 清空相关字段
                    $('#matters-settings input, #matters-settings textarea, #matters-settings select').val('');
                }
            });

            // 监听“课程表项目名称”下拉框选项更新，若为空则显示占位项
            function ensureFormalOption(select) {
                var $sel = $(select);
                if ($sel.length === 0) return;
                var $options = $sel.find('option');
                if ($options.length === 0) {
                    $sel.append('<option value="0">尚未有正式排课项目</option>');
                } else if ($options.length > 1 && $options.first().val() === '0') {
                    // 有真实选项时移除占位项
                    $options.first().remove();
                }
            }

            function observeSelectOptions(select) {
                var el = document.querySelector(select);
                if (!el) return;
                var obs = new MutationObserver(function (mutations) {
                    mutations.forEach(function (m) {
                        if (m.type === 'childList') {
                            ensureFormalOption(select);
                        }
                    });
                });
                obs.observe(el, { childList: true });
                // 初始化检查
                ensureFormalOption(select);
            }

            // 对学校与社区两类课程表下拉框进行观察
            observeSelectOptions('#c-table_id');
            observeSelectOptions('#c-publicwelfare_id');

            // 添加班级项目动态管理
            var classItemIndex = 1;
            $(document).on('click', '#add-class-item', function () {
                debugger;
                var newItem = `
                    <div class="class-import-item" style="border: 1px solid #ddd; padding: 20px; margin-bottom: 20px; border-radius: 6px; background: #fafafa;">
                        <div class="row" style="margin-bottom: 15px;">
                            <div class="col-md-6">
                                <div class="form-group" style="margin-bottom: 15px; margin-right: 10px;">
                                    <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">班级:</label>
                                    <select id="c-classes_id" name="row[class_items][${classItemIndex}][class_id]" class="form-control classes-select" style="height: 36px;">
                                        <option value="">请选择班级</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group" style="margin-bottom: 15px; margin-left: 10px;">
                                    <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">教学点:</label>
                                    <select id="c-ocation_class" name="row[class_items][${classItemIndex}][teaching_point]" class="form-control teaching-point-select" style="height: 36px;">
                                        <option value="">请选择教学点</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row" style="margin-bottom: 15px;">
                            <div class="col-md-4">
                                <div class="form-group" style="margin-bottom: 15px; margin-right: 10px;">
                                    <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">上课时间:</label>
                                    <input type="text" name="row[class_items][${classItemIndex}][class_time]" class="form-control" style="height: 36px;" placeholder="请输入上课时间" />
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group" style="margin-bottom: 15px; margin-left: 5px; margin-right: 5px;">
                                    <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">课程类型:</label>
                                    <select name="row[class_items][${classItemIndex}][course_type]" class="form-control" style="height: 36px;">
                                        <option value="1">课程</option>
                                        <option value="2">活动</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group" style="margin-bottom: 15px; margin-left: 10px;">
                                    <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">费用:</label>
                                    <input type="number" name="row[class_items][${classItemIndex}][fee]" class="form-control" style="height: 36px;" placeholder="请输入费用" step="0.01" />
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group" style="margin-bottom: 10px; margin-right: 10px;">
                                    <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">名额:</label>
                                    <input type="number" name="row[class_items][${classItemIndex}][quota]" class="form-control" style="height: 36px;" placeholder="请输入名额" />
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group" style="margin-top: 30px; margin-left: 10px; text-align: right;">
                                        <button type="button" class="btn-save-class-custom save-class-item" style="padding: 6px 12px; margin-right: 10px; background-color: #5cb85c; color: white; border: 1px solid #4cae4c; border-radius: 4px; cursor: pointer;">
                                            <i class="fa fa-save"></i> 保存班级
                                        </button>
                                        <button type="button" class="btn btn-danger btn-sm remove-class-item" style="padding: 6px 12px;">
                                            <i class="fa fa-trash"></i> 删除此项
                                        </button>
                                    </div>
                            </div>
                        </div>
                    </div>
                `;
                $('#class-import-items').append(newItem);
                classItemIndex++;
            });

            // 保存班级到课程表
            $(document).on('click', '.save-class-item', function () {
                var $classItem = $(this).closest('.class-import-item');
                var classData = {
                    table_id: $("#c-classes_id").val(),
                    publicwelfare_id: $("#c-publicwelfare_id").val(),
                    apply_type: $('input[name="row[apply_type]"]:checked').val(),
                    apply_id: $('#apply_id').val(),
                    id: $classItem.find('input[name*="[id]"]').val(),
                    classes_type: $('input[name="row[course_type]"]:checked').val(),
                    class_id: $classItem.find('select[name*="[class_id]"]').val(),
                    teaching_point: $classItem.find('select[name*="[teaching_point]"]').val(),
                    class_time: $classItem.find('input[name*="[class_time]"]').val(),
                    course_type: $classItem.find('select[name*="[course_type]"]').val(),
                    fee: $classItem.find('input[name*="[fee]"]').val(),
                    quota: $classItem.find('input[name*="[quota]"]').val()
                };

                // 验证必填字段
                if (!classData.class_id) {
                    Layer.msg('请选择班级', { icon: 2 });
                    return;
                }
                if (!classData.teaching_point) {
                    Layer.msg('请选择教学点', { icon: 2 });
                    return;
                }
                if (!classData.class_time) {
                    Layer.msg('请输入上课时间', { icon: 2 });
                    return;
                }

                // 显示加载状态
                var $btn = $(this);
                var originalText = $btn.html();
                $btn.html('<i class="fa fa-spinner fa-spin"></i> 保存中...').prop('disabled', true);

                // 发送POST请求
                $.ajax({
                    url: 'autoplantemp/autoplantemp/classesadd',
                    type: 'POST',
                    data: classData,
                    dataType: 'json',
                    success: function (response) {
                        if (response.code === 1) {
                            Layer.msg('班级保存成功', { icon: 1 });
                        } else {
                            Layer.msg(response.msg || '保存失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        Layer.msg('网络错误，请重试', { icon: 2 });
                        console.error('保存班级失败:', error);
                    },
                    complete: function () {
                        // 恢复按钮状态
                        $btn.html(originalText).prop('disabled', false);
                    }
                });
            });

            // 删除班级项目
            // 删除班级项目（编辑页面）
            $(document).on('click', '.remove-class-item', function () {
                if ($('.class-import-item').length > 1) {
                    // 发送POST请求
                    $.ajax({
                        url: 'autoplantemp/autoplantemp/classesdel',
                        type: 'POST',
                        data: classData,
                        dataType: 'json',
                        success: function (response) {
                            if (response.code === 1 || response.code === 200) {
                                Layer.msg('删除成功', { icon: 1 });
                                // 可以在这里添加成功后的处理逻辑
                                $(this).closest('.class-import-item').remove();
                            } else {
                                Layer.msg(response.msg || '保存失败', { icon: 2 });
                            }
                        },
                        error: function (xhr, status, error) {
                            Layer.msg('网络错误，保存失败', { icon: 2 });
                            console.error('删除班级失败:', error);
                        },
                        complete: function () {
                            // 恢复按钮状态
                            $btn.html(originalText).prop('disabled', false);
                        }
                    });
                } else {
                    Layer.msg('至少保留一个班级项目');
                }
            });

            // 教学点数据同步功能
            function syncTeachingPointOptions() {
                var masterSelect = $('#c-ocation_class');
                if (masterSelect.length > 0 && masterSelect.find('option').length > 1) {
                    var options = masterSelect.html();
                    // 同步到所有其他教学点下拉框
                    $('.teaching-point-select, select[name*="teaching_point"]').not('#c-ocation_class').each(function () {
                        var currentValue = $(this).val();
                        $(this).html(options);
                        // 恢复之前选中的值
                        if (currentValue) {
                            $(this).val(currentValue);
                        }
                    });
                }
            }

            // 班级数据同步功能
            function syncClassesOptions() {
                var masterSelect = $('#c-classes_id');
                if (masterSelect.length > 0 && masterSelect.find('option').length > 1) {
                    var options = masterSelect.html();
                    // 同步到所有其他班级下拉框
                    $('.classes-select, select[name*="class_id"]').not('#c-classes_id').each(function () {
                        var currentValue = $(this).val();
                        $(this).html(options);
                        // 恢复之前选中的值
                        if (currentValue) {
                            $(this).val(currentValue);
                        }
                    });
                }
            }

            // 监听主教学点下拉框的数据变化
            $(document).on('DOMNodeInserted', '#c-ocation_class', function () {
                syncTeachingPointOptions();
            });

            // 监听主班级下拉框的数据变化
            $(document).on('DOMNodeInserted', '#c-classes_id', function () {
                syncClassesOptions();
            });

            // 监听主教学点下拉框的选项更新
            var observer = new MutationObserver(function (mutations) {
                mutations.forEach(function (mutation) {
                    if (mutation.type === 'childList' && mutation.target.id === 'c-ocation_class') {
                        syncTeachingPointOptions();
                    }
                    if (mutation.type === 'childList' && mutation.target.id === 'c-classes_id') {
                        syncClassesOptions();
                    }
                });
            });

            // 开始观察主教学点下拉框和主班级下拉框
            $(document).ready(function () {
                var masterTeachingPointSelect = document.getElementById('c-ocation_class');
                var masterClassesSelect = document.getElementById('c-classes_id');
                if (masterTeachingPointSelect) {
                    observer.observe(masterTeachingPointSelect, { childList: true, subtree: true });
                }
                if (masterClassesSelect) {
                    observer.observe(masterClassesSelect, { childList: true, subtree: true });
                }
            });

            // 添加新项目后同步教学点选项和班级选项
            $(document).on('click', '#add-class-item', function () {
                debugger;
                setTimeout(function () {
                    syncTeachingPointOptions();
                    syncClassesOptions();
                }, 100);
            });

            // 添加线下报名switcher事件处理
            $(document).on('change', '#c-enable_offline_registration', function () {
                var isEnabled = $(this).val() == '1';
                if (isEnabled) {
                    $('#offline-registration-settings').show();
                } else {
                    $('#offline-registration-settings').hide();
                    // 清空相关字段
                    $('#offline-registration-settings input').val('');
                }
            });

            // 添加报名条件switcher事件处理
            $(document).on('change', '#c-enable_registration_conditions', function () {
                var isEnabled = $(this).val() == '1';
                if (isEnabled) {
                    $('#registration-conditions-settings').show();
                } else {
                    $('#registration-conditions-settings').hide();
                    // 清空相关字段
                    $('#registration-conditions-settings input, #registration-conditions-settings textarea').val('');
                }
            });

            // 添加报名须知开关事件处理
            $(document).on('change', '#c-enable_terms_agreement', function () {
                var isEnabled = $(this).val() == '1';
                if (isEnabled) {
                    $('#terms-agreement-settings').show();
                } else {
                    $('#terms-agreement-settings').hide();
                    // 清空相关字段
                    $('#terms-agreement-settings input, #terms-agreement-settings textarea').val('');
                }
            });

            // 页面加载时检查switcher状态
            $(document).ready(function () {
                // 检查报名类型状态
                var applyType = $('input[name="row[apply_type]"]:checked').val();
                if (applyType == '1') {
                    $('#course-type-group').show();
                } else {
                    $('#course-type-group').hide();
                }

                // 检查分阶段报名状态
                var isStagedEnabled = $('#c-is_staged').val() == '1';
                if (isStagedEnabled) {
                    $('#staged-names').show();
                    $('#staged-registration-info').show();
                } else {
                    $('#staged-names').hide();
                    $('#staged-registration-info').hide();
                }

                // 检查报名数量限制状态
                var isQuantityLimitEnabled = $('#c-enable_quantity_limit').val() == '1';
                if (isQuantityLimitEnabled) {
                    $('#quantity-limit-settings').show();
                } else {
                    $('#quantity-limit-settings').hide();
                }

                // 检查报名表开启状态
                var isRegistrationFormEnabled = $('#c-enable_registration_form').val() == '1';
                if (isRegistrationFormEnabled) {
                    $('#registration-form-settings').show();
                } else {
                    $('#registration-form-settings').hide();
                }

                // 检查手签板状态
                var isSignaturePadEnabled = $('#c-enable_signature_pad').val() == '1';
                if (isSignaturePadEnabled) {
                    $('#signature-pad-settings').show();
                } else {
                    $('#signature-pad-settings').hide();
                }

                // 检查事项设置状态
                var isMattersSettingEnabled = $('#c-enable_matters_setting').val() == '1';
                if (isMattersSettingEnabled) {
                    $('#matters-settings').show();
                } else {
                    $('#matters-settings').hide();
                }

                // 检查线下报名状态
                var isOfflineRegistrationEnabled = $('#c-enable_offline_registration').val() == '1';
                if (isOfflineRegistrationEnabled) {
                    $('#offline-registration-settings').show();
                } else {
                    $('#offline-registration-settings').hide();
                }

                // 检查报名条件状态
                var isRegistrationConditionsEnabled = $('#c-enable_registration_conditions').val() == '1';
                if (isRegistrationConditionsEnabled) {
                    $('#registration-conditions-settings').show();
                } else {
                    $('#registration-conditions-settings').hide();
                }

                // 检查报名须知状态
                var isTermsAgreementEnabled = $('#c-enable_terms_agreement').val() == '1';
                if (isTermsAgreementEnabled) {
                    $('#terms-agreement-settings').show();
                } else {
                    $('#terms-agreement-settings').hide();
                }
            });

            // 根据课堂类型切换课程表下拉框显示
            function updateTableSelectVisibility() {
                var typeVal = $('input[name="row[table_type]"]:checked').val();
                var t1 = (typeVal === '1');
                var t2 = (typeVal === '2');

                if ($('#c-table_id').length > 0) {
                    $('#c-table_id').closest('div').find('#c-table_id').toggle(t1);
                }
                if ($('#c-publicwelfare_id').length > 0) {
                    $('#c-publicwelfare_id').closest('div').find('#c-publicwelfare_id').toggle(t2);
                }
                // 触发数据加载
                if (t1 && $('#c-table_id').length > 0) {
                    $('#c-table_id').trigger('change2');
                }
                if (t2 && $('#c-publicwelfare_id').length > 0) {
                    $('#c-publicwelfare_id').trigger('change2');
                }
            }

            // 监听课堂类型切换
            $(document).on('change', 'input[name="row[table_type]"]', function () {
                updateTableSelectVisibility();
            });

            // 页面初始化时设置显示状态
            $(function () {
                if ($('input[name="row[table_type]"]').length > 0) {
                    // 若未选中，默认选学校=1
                    if ($('input[name="row[table_type]"]:checked').length === 0) {
                        $('input[name="row[table_type]"][value="1"]').prop('checked', true);
                    }
                    updateTableSelectVisibility();
                }
            });


            Controller.api.bindevent();
        },
        edit: function () {
            var row = JSON.parse($('#row').val());


            // 教学点数据同步功能（编辑页面）
            function syncTeachingPointOptionsEdit() {
                var masterSelect = $('#c-ocation_class');
                var options = "";
                if (masterSelect.length > 0) {
                    $("#c-ocation_class").trigger("change2");
                }
                setTimeout(function () {
                    options = $('#c-ocation_class').html();
                    $('.teaching-point-select:not(:first)').each(function () {
                        var currentValue = $(this).data("default");
                        $(this).html(options);
                        if (currentValue) {
                            $(this).val(currentValue);
                        }
                    });
                }, 500);

            }

            // 班级数据同步功能（编辑页面）
            function syncClassesOptionsEdit() {
                var masterSelect = $('#c-classes_id');
                var options = "";
                if (masterSelect.length > 0) {
                    $("#c-classes_id").trigger("change2");
                }
                setTimeout(function () {
                    options = $('#c-classes_id').html();
                    $('.classes-select:not(:first)').each(function () {
                        var currentValue = $(this).data("default");
                        $(this).html(options);
                        if (currentValue) {
                            $(this).val(currentValue);
                        }
                    });
                }, 500);

            }

            // 动态加载班级数据
            function loadClassItems() {
                var apply_id = $('#apply_id').val();
                if (!apply_id) {
                    console.error('apply_id not found');
                    return;
                }
                $.ajax({
                    url: '/autoplantemp/Autoplantemp/classeslist',
                    type: 'GET',
                    data: {
                        apply_id: apply_id
                    },
                    dataType: 'json',
                    success: function (response) {
                        $('#loading-indicator').hide();
                        if (response.code === 1 && response.data) {
                            renderClassItems(response.data);
                            setTimeout(function () {
                                syncTeachingPointOptionsEdit();
                                syncClassesOptionsEdit();
                            }, 1000);
                        } else {
                            $('#class-items-container').html('<div class="alert alert-info">暂无班级数据</div>');
                        }

                    },
                    error: function (xhr, status, error) {
                        $('#loading-indicator').hide();
                        console.error('加载班级数据失败:', error);
                        $('#class-items-container').html('<div class="alert alert-danger">加载班级数据失败，请刷新页面重试</div>');
                    }
                });
            }

            // 渲染班级数据
            function renderClassItems(classItems) {
                var container = $('#class-items-container');
                container.empty();
                // 如果没有数据，至少显示一个空项
                if (!classItems || classItems.length === 0) {
                    classItems = [{}]; // 创建一个空对象作为默认项
                }

                classItems.forEach(function (item, index) {
                    var classItemHtml = `
                        <div class="class-import-item class-item" data-index="${index}" style="border: 1px solid #ddd; padding: 20px; margin-bottom: 20px; border-radius: 6px; background: #fafafa;">
                            <div class="row" style="margin-bottom: 15px;">
                            <input type="hidden" name="row[class_items][${index}][id]" value="${item.id}">
                                <div class="col-md-6">
                                    <div class="form-group" style="margin-bottom: 15px; margin-right: 10px;">
                                        <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">班级:</label>
                                        <select name="row[class_items][${index}][class_id]" ${index == 0 ? 'id="c-classes_id"' : ''} data-index="${index}"  data-default="${item.class_id}"  class="form-control classes-select" style="height: 36px;">
                                            <option value="">请选择班级</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group" style="margin-bottom: 15px; margin-left: 10px;">
                                        <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">教学点:</label>
                                        <select name="row[class_items][${index}][teaching_point]" ${index == 0 ? 'id="c-ocation_class"' : ''} data-index="${index}"  data-default="${item.location_id}"  class="form-control  teaching-point-select" style="height: 36px;">
                                            <option value="">请选择教学点</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="row" style="margin-bottom: 15px;">
                                <div class="col-md-4">
                                    <div class="form-group" style="margin-bottom: 15px; margin-right: 10px;">
                                        <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">上课时间:</label>
                                        <input type="text" name="row[class_items][${index}][class_time]" 
                                            value="${item.class_time || ''}" class="form-control" style="height: 36px;" placeholder="请输入上课时间" />
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group" style="margin-bottom: 15px; margin-left: 5px; margin-right: 5px;">
                                        <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">课程类型:</label>
                                        <select name="row[class_items][${index}][course_type]" class="form-control" style="height: 36px;">
                                            <option value="1" ${(item.course_type == '1') ? 'selected' : ''}>课程</option>
                                            <option value="2" ${(item.course_type == '2') ? 'selected' : ''}>活动</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group" style="margin-bottom: 15px; margin-left: 10px;">
                                        <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">费用:</label>
                                        <input type="number" name="row[class_items][${index}][fee]" 
                                            value="${item.fee || ''}" class="form-control" style="height: 36px;" placeholder="请输入费用" step="0.01" />
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group" style="margin-bottom: 10px; margin-right: 10px;">
                                        <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">名额:</label>
                                        <input type="number" name="row[class_items][${index}][quota]" 
                                            value="${item.quota || ''}" class="form-control" style="height: 36px;" placeholder="请输入名额" />
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group" style="margin-top: 30px; margin-left: 10px; text-align: right;">
                                        <button type="button" class="btn-save-class-custom save-class-item" data-index="${index}" style="padding: 6px 12px; margin-right: 10px; background-color: #5cb85c; color: white; border: 1px solid #4cae4c; border-radius: 4px; cursor: pointer;">
                                            <i class="fa fa-save"></i> 保存班级
                                        </button>
                                        <button type="button" class="btn btn-danger btn-sm remove-class-item" data-index="${index}" style="padding: 6px 12px;">
                                            <i class="fa fa-trash"></i> 删除此项
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                    container.append(classItemHtml);
                });
                syncTeachingPointOptionsEdit();
                syncClassesOptionsEdit();
                // 绑定事件
                bindClassItemEvents();
            }

            // 绑定班级项目相关事件
            function bindClassItemEvents() {
                // 保存班级项目事件
                $(document).off('click', '.save-class-item').on('click', '.save-class-item', function () {
                    var index = $(this).data('index');
                    var classItem = $(`.class-item[data-index="${index}"]`);
                    debugger;
                    var apply_id = $('#apply_id').val();
                    var apply_type = $('input[name="row[apply_type]"]:checked').val();
                    var data = {
                        table_id: $("#c-classes_id").val(),
                        publicwelfare_id: $("#c-publicwelfare_id").val(),
                        apply_type: $('input[name="row[apply_type]"]:checked').val(),
                        apply_id: $('#apply_id').val(),
                        id: classItem.find('input[name*="[id]"]').val(),
                        classes_id: classItem.find('select[name*="[class_id]"]').val(),
                        location_id: classItem.find('select[name*="[teaching_point]"]').val(),
                        class_time: classItem.find('input[name*="[class_time]"]').val(),
                        course_type: classItem.find('select[name*="[course_type]"]').val(),
                        fee: classItem.find('input[name*="[fee]"]').val(),
                        quota: classItem.find('input[name*="[quota]"]').val(),
                        classes_type: 1 // 默认值
                    };

                    // 验证必填字段
                    if (!data.classes_id) {
                        Toastr.error('请选择班级');
                        return;
                    }
                    if (!data.location_id) {
                        Toastr.error('请选择教学点');
                        return;
                    }

                    var btn = $(this);
                    btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 保存中...');

                    $.ajax({
                        url: '/autoplantemp/autoplantemp/classesadd',
                        type: 'POST',
                        data: data,
                        dataType: 'json',
                        success: function (response) {
                            if (response.code === 1) {
                                Toastr.success('保存成功');
                                // 重新加载班级数据
                                loadClassItems();
                            } else {
                                Fast.events.customToastr(response.msg, "保存失败", "error", {
                                    align: "center",
                                    width: "800px",
                                    top: "80px"
                                });
                            }
                        },
                        error: function () {
                            Toastr.error('保存失败，请重试');
                        },
                        complete: function () {
                            btn.prop('disabled', false).html('<i class="fa fa-save"></i> 保存');
                        }
                    });
                });

                // 删除班级项目事件
                $(document).off('click', '.delete-class-item').on('click', '.delete-class-item', function () {
                    var index = $(this).data('index');
                    var id = $(this).data('id');
                    if (confirm('确定要删除这个班级项目吗？')) {
                        if (id) {
                            // 如果有ID，调用删除接口
                            $.ajax({
                                url: '/autoplantemp/autoplantemp/classesdelete',
                                type: 'POST',
                                data: { id: id },
                                dataType: 'json',
                                success: function (response) {
                                    if (response.code === 1) {
                                        Toastr.success('删除成功');
                                        loadClassItems();
                                    } else {
                                        Toastr.error(response.msg || '删除失败');
                                    }
                                },
                                error: function () {
                                    Toastr.error('删除失败，请重试');
                                }
                            });
                        } else {
                            // 如果没有ID，直接从页面移除
                            $(`.class-item[data-index="${index}"]`).remove();
                        }
                    }
                });
            }

            // 添加班级项目事件
            $(document).off('click', '#add-class-item').on('click', '#add-class-item', function () {
                debugger;
                var container = $('#class-items-container');
                var index = container.find('.class-item').length;
                var newItemHtml = `
                    <div class="class-item" data-index="${index}">
                        <div class="row">
                            <div class="col-xs-2">
                                <div class="form-group">
                                    <label class="control-label">班级</label>
                                    <select class="form-control classes-select" id="c-classes_id" name="class_items[${index}][classes_id]">
                                        <option value="">请选择班级</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-xs-2">
                                <div class="form-group">
                                    <label class="control-label">教学点</label>
                                    <select id="c-ocation_class" class="form-control location-select" name="class_items[${index}][location_id]">
                                        <option value="">请选择教学点</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-xs-2">
                                <div class="form-group">
                                    <label class="control-label">上课时间</label>
                                    <input type="text" class="form-control" name="class_items[${index}][class_time]" placeholder="请输入上课时间">
                                </div>
                            </div>
                            <div class="col-xs-1">
                                <div class="form-group">
                                    <label class="control-label">课程类型</label>
                                    <select class="form-control" name="class_items[${index}][course_type]">
                                        <option value="1">线上</option>
                                        <option value="2">线下</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-xs-1">
                                <div class="form-group">
                                    <label class="control-label">费用</label>
                                    <input type="number" class="form-control" name="class_items[${index}][fee]" placeholder="费用" step="0.01">
                                </div>
                            </div>
                            <div class="col-xs-1">
                                <div class="form-group">
                                    <label class="control-label">名额</label>
                                    <input type="number" class="form-control" name="class_items[${index}][quota]" placeholder="名额">
                                </div>
                            </div>
                            <div class="col-xs-2">
                                <div class="form-group">
                                    <label class="control-label">操作</label>
                                    <div>
                                        <button type="button" class="btn btn-primary btn-xs save-class-item" data-index="${index}">
                                            <i class="fa fa-save"></i> 保存
                                        </button>
                                        <button type="button" class="btn btn-danger btn-xs delete-class-item" data-index="${index}">
                                            <i class="fa fa-trash"></i> 删除
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;

                container.append(newItemHtml);
                bindClassItemEvents();
            });

            // 页面加载时自动加载班级数据
            $(document).ready(function () {

                // 当切换到班级信息选项卡时加载数据
                $('a[href="#class-import-edit"]').on('shown.bs.tab', function () {
                    loadClassItems();
                });


                // 添加选项卡初始化和事件处理
                // 初始化选项卡
                $('.nav-tabs a').click(function (e) {
                    e.preventDefault();
                    $(this).tab('show');
                });

                // 报名类型切换逻辑
                $('input[name="row[apply_type]"]').change(function () {
                    var applyType = $(this).val();
                    if (applyType == '1') {
                        $('#course-type-group').show();
                    } else {
                        $('#course-type-group').hide();
                        $('input[name="row[course_type]"]').prop('checked', false);
                    }
                });

                // 分阶段报名逻辑
                $('#c-is_staged').change(function () {
                    if ($(this).val() == '1') {
                        $('#staged-names').show();
                        $('#staged-registration-info').show();
                    } else {
                        $('#staged-names').hide();
                        $('#staged-registration-info').hide();
                    }
                });

                // 报名数量限制逻辑
                $('#c-enable_quantity_limit').change(function () {
                    if ($(this).val() == '1') {
                        $('#quantity-limit-settings').show();
                    } else {
                        $('#quantity-limit-settings').hide();
                    }
                });

                // 报名表开启逻辑
                $('#c-enable_registration_form').change(function () {
                    if ($(this).val() == '1') {
                        $('#registration-form-settings').show();
                    } else {
                        $('#registration-form-settings').hide();
                    }
                });

                // 手签板逻辑
                $('#c-enable_signature_pad').change(function () {
                    if ($(this).val() == '1') {
                        $('#signature-pad-settings').show();
                    } else {
                        $('#signature-pad-settings').hide();
                    }
                });

                // 事项设置逻辑
                $('#c-enable_matters_setting').change(function () {
                    if ($(this).val() == '1') {
                        $('#matters-settings').show();
                    } else {
                        $('#matters-settings').hide();
                    }
                });

                // 特殊报名通道开关逻辑
                $('#c-enable_special_channel').change(function () {
                    if ($(this).val() == '1') {
                        $('#special-channel-settings').show();
                    } else {
                        $('#special-channel-settings').hide();
                    }
                });

                // 特殊报名通道适用范围切换
                $('#c-special_channel_scope').change(function () {
                    if ($(this).val() == 'specific') {
                        $('#specific-classes-group').show();
                        // 加载课程列表
                        loadClassesForSpecialChannel();
                    } else {
                        $('#specific-classes-group').hide();
                    }
                });

                // 加载课程列表用于特殊通道
                function loadClassesForSpecialChannel() {
                    var tableId = $('#c-table_id').val() || $('#c-publicwelfare_id').val();
                    if (!tableId) return;

                    $.ajax({
                        url: '/autoplantemp/Autoplantemp/classeslist',
                        type: 'GET',
                        data: { table_id: tableId },
                        dataType: 'json',
                        success: function (response) {
                            if (response.code === 1 && response.data) {
                                var $select = $('#c-special_channel_classes');
                                $select.empty();
                                response.data.forEach(function (item) {
                                    $select.append('<option value="' + item.id + '">' + item.name + '</option>');
                                });
                                // 刷新selectpicker
                                if ($select.hasClass('selectpicker')) {
                                    $select.selectpicker('refresh');
                                }
                            }
                        }
                    });
                }

                // 页面加载时检查特殊报名通道状态
                if ($('#c-enable_special_channel').val() == '1') {
                    $('#special-channel-settings').show();
                    if ($('#c-special_channel_scope').val() == 'specific') {
                        $('#specific-classes-group').show();
                        loadClassesForSpecialChannel();
                    }
                }




                // 班级导入 添加班级项目动态管理（编辑页面）

                $(document).on('click', '#add-class-item-edit', function () {
                    debugger;
                    var classItemIndexEdit = $('.class-import-item').length;
                    var newItem = `
                        <div class="class-import-item class-item" data-index="${classItemIndexEdit}" style="border: 1px solid #ddd; padding: 20px; margin-bottom: 20px; border-radius: 6px; background: #fafafa;">
                            <div class="row" style="margin-bottom: 15px;">
                                <div class="col-md-6">
                                    <div class="form-group" style="margin-bottom: 15px; margin-right: 10px;">
                                        <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">班级:</label>
                                        <select  id="c-classes_id" name="row[class_items][${classItemIndexEdit}][class_id]" data-index="${classItemIndexEdit}" class="form-control classes-select" style="height: 36px;">
                                            <option value="">请选择班级</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group" style="margin-bottom: 15px; margin-left: 10px;">
                                        <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">教学点:</label>
                                        <select id="c-ocation_class" name="row[class_items][${classItemIndexEdit}][teaching_point]"data-index="${classItemIndexEdit}" class="form-control teaching-point-select" style="height: 36px;">
                                            <option value="">请选择教学点</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="row" style="margin-bottom: 15px;">
                                <div class="col-md-4">
                                    <div class="form-group" style="margin-bottom: 15px; margin-right: 10px;">
                                        <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">上课时间:</label>
                                        <input type="text" name="row[class_items][${classItemIndexEdit}][class_time]" class="form-control" style="height: 36px;" placeholder="请输入上课时间" />
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group" style="margin-bottom: 15px; margin-left: 5px; margin-right: 5px;">
                                        <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">课程类型:</label>
                                        <select name="row[class_items][${classItemIndexEdit}][course_type]" class="form-control" style="height: 36px;">
                                            <option value="1">课程</option>
                                            <option value="2">活动</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group" style="margin-bottom: 15px; margin-left: 10px;">
                                        <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">费用:</label>
                                        <input type="number" name="row[class_items][${classItemIndexEdit}][fee]" class="form-control" style="height: 36px;" placeholder="请输入费用" step="0.01" />
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group" style="margin-bottom: 10px; margin-right: 10px;">
                                        <label class="control-label" style="margin-bottom: 8px; font-weight: 600;">名额:</label>
                                        <input type="number" name="row[class_items][${classItemIndexEdit}][quota]" class="form-control" style="height: 36px;" placeholder="请输入名额" />
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group" style="margin-top: 30px; margin-left: 10px; text-align: right;">
                                        <button type="button" class="btn-save-class-custom save-class-item" data-index="${classItemIndexEdit}" style="padding: 6px 12px; margin-right: 10px; background-color: #5cb85c; color: white; border: 1px solid #4cae4c; border-radius: 4px; cursor: pointer;">
                                            <i class="fa fa-save"></i> 保存班级
                                        </button>
                                        <button type="button" class="btn btn-danger btn-sm remove-class-item" data-index="${classItemIndexEdit}" style="padding: 6px 12px;">
                                            <i class="fa fa-trash"></i> 删除此项
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                    $('#class-items-container').append(newItem);
                    classItemIndexEdit++;
                    // 添加新项目后立即同步下拉框数据
                    setTimeout(function () {
                        syncTeachingPointOptionsEdit();
                        syncClassesOptionsEdit();
                    }, 100);
                });

                // 保存班级到课程表（编辑页面）
                $(document).on('click', '.save-class-item', function () {
                    var $classItem = $(this).closest('.class-import-item');
                    var classData = {
                        id: $classItem.find('input[name*="[id]"]').val(),
                        table_id: $("#c-classes_id").val(),
                        publicwelfare_id: $("#c-publicwelfare_id").val(),
                        apply_type: $('input[name="row[apply_type]"]:checked').val(),
                        apply_id: $('#apply_id').val(),
                        classes_type: $('input[name="row[course_type]"]:checked').val(),
                        class_id: $classItem.find('select[name*="[class_id]"]').val(),
                        teaching_point: $classItem.find('select[name*="[teaching_point]"]').val(),
                        class_time: $classItem.find('input[name*="[class_time]"]').val(),
                        course_type: $classItem.find('select[name*="[course_type]"]').val(),
                        fee: $classItem.find('input[name*="[fee]"]').val(),
                        quota: $classItem.find('input[name*="[quota]"]').val()
                    };

                    // 验证必填字段

                    if (!classData.class_id) {
                        Layer.msg('请选择班级', { icon: 2 });
                        return;
                    }
                    if (!classData.teaching_point) {
                        Layer.msg('请选择教学点', { icon: 2 });
                        return;
                    }
                    if (!classData.class_time) {
                        Layer.msg('请输入上课时间', { icon: 2 });
                        return;
                    }

                    // 显示加载状态
                    var $btn = $(this);
                    var originalText = $btn.html();
                    $btn.html('<i class="fa fa-spinner fa-spin"></i> 保存中...').prop('disabled', true);

                    // 发送POST请求
                    $.ajax({
                        url: 'autoplantemp/autoplantemp/classesadd',
                        type: 'POST',
                        data: classData,
                        dataType: 'json',
                        success: function (response) {
                            if (response.code === 1 || response.code === 200) {
                                Layer.msg('班级保存成功', { icon: 1 });
                                // 可以在这里添加成功后的处理逻辑
                            } else {
                                Layer.msg(response.msg || '保存失败', { icon: 2 });
                            }
                        },
                        error: function (xhr, status, error) {
                            Layer.msg('网络错误，保存失败', { icon: 2 });
                            console.error('保存班级失败:', error);
                        },
                        complete: function () {
                            // 恢复按钮状态
                            $btn.html(originalText).prop('disabled', false);
                        }
                    });
                });

                // 删除班级项目（编辑页面）
                $(document).on('click', '.remove-class-item', function () {
                    if ($('.class-import-item').length > 1) {
                        // 显示加载状态
                        var $btn = $(this);
                        var originalText = $btn.html();
                        $btn.html('<i class="fa fa-spinner fa-spin"></i> 删除中...').prop('disabled', true);

                        var $classItem = $(this).closest('.class-import-item');
                        var classData = {
                            apply_type: $('input[name="row[apply_type]"]:checked').val(),
                            apply_id: $('#apply_id').val(),
                            classes_type: $('input[name="row[course_type]"]:checked').val(),
                            id: $classItem.find('input[name*="[id]"]').val(),
                            class_id: $classItem.find('select[name*="[class_id]"]').val(),
                            teaching_point: $classItem.find('select[name*="[teaching_point]"]').val(),
                            class_time: $classItem.find('input[name*="[class_time]"]').val(),
                            course_type: $classItem.find('select[name*="[course_type]"]').val(),
                            fee: $classItem.find('input[name*="[fee]"]').val(),
                            quota: $classItem.find('input[name*="[quota]"]').val()
                        };
                        if ($classItem.find('input[name*="[id]"]').length == 0 || $classItem.find('input[name*="[id]"]').val() == "undefined") {
                            $classItem.remove();
                            return;
                        } else {
                            // 发送POST请求
                            $.ajax({
                                url: 'autoplantemp/autoplantemp/classesdel',
                                type: 'POST',
                                data: classData,
                                dataType: 'json',
                                success: function (response) {
                                    if (response.code === 1 || response.code === 200) {
                                        Layer.msg('删除成功', { icon: 1 });
                                        $classItem.remove();
                                        loadClassItems();
                                    } else {
                                        Layer.msg(response.msg || '删除失败', { icon: 2 });
                                    }
                                },
                                error: function (xhr, status, error) {
                                    Layer.msg('网络错误，删除失败', { icon: 2 });
                                    console.error('删除班级失败:', error);
                                },
                                complete: function () {
                                    // 恢复按钮状态
                                    $btn.html(originalText).prop('disabled', false);
                                }
                            });
                        }
                    } else {
                        Layer.msg('至少保留一个班级项目');
                    }
                });



                // 监听主教学点下拉框和主班级下拉框的选项更新（编辑页面）
                var observerEdit = new MutationObserver(function (mutations) {
                    mutations.forEach(function (mutation) {
                        if (mutation.type === 'childList' && mutation.target.id === 'c-ocation_class') {
                            syncTeachingPointOptionsEdit();
                        }
                        if (mutation.type === 'childList' && mutation.target.id === 'c-classes_id') {
                            syncClassesOptionsEdit();
                        }
                    });
                });

                // 开始观察主教学点下拉框和主班级下拉框（编辑页面）
                var masterTeachingPointSelectEdit = document.getElementById('c-ocation_class');
                var masterClassesSelectEdit = document.getElementById('c-classes_id');
                if (masterTeachingPointSelectEdit) {
                    observerEdit.observe(masterTeachingPointSelectEdit, { childList: true, subtree: true });
                }
                if (masterClassesSelectEdit) {
                    observerEdit.observe(masterClassesSelectEdit, { childList: true, subtree: true });
                }

                // 添加新项目后同步教学点选项和班级选项（编辑页面）
                $(document).on('click', '#add-class-item-edit', function () {
                    debugger;
                    setTimeout(function () {
                        syncTeachingPointOptionsEdit();
                        syncClassesOptionsEdit();
                    }, 100);
                });

                // 线下报名逻辑
                $('#c-enable_offline_registration').change(function () {
                    if ($(this).val() == '1') {
                        $('#offline-registration-settings').show();
                    } else {
                        $('#offline-registration-settings').hide();
                    }
                });

                // 报名条件逻辑
                $('#c-enable_registration_conditions').change(function () {
                    if ($(this).val() == '1') {
                        $('#registration-conditions-settings').show();
                    } else {
                        $('#registration-conditions-settings').hide();
                    }
                });

                // 报名须知逻辑
                $('#c-enable_terms_agreement').change(function () {
                    if ($(this).val() == '1') {
                        $('#terms-agreement-settings').show();
                    } else {
                        $('#terms-agreement-settings').hide();
                    }
                });

                // 初始化时检查报名类型状态
                var applyType = $('input[name="row[apply_type]"]:checked').val();
                if (applyType == '1') {
                    $('#course-type-group').show();
                } else {
                    $('#course-type-group').hide();
                }

                // 初始化时检查分阶段状态
                if ($('#c-is_staged').val() == '1') {
                    $('#staged-names').show();
                    $('#staged-registration-info').show();
                } else {
                    $('#staged-names').hide();
                    $('#staged-registration-info').hide();
                }

                // 初始化时检查报名数量限制状态
                if ($('#c-enable_quantity_limit').val() == '1') {
                    $('#quantity-limit-settings').show();
                } else {
                    $('#quantity-limit-settings').hide();
                }

                // 初始化时检查报名表开启状态
                if ($('#c-enable_registration_form').val() == '1') {
                    $('#registration-form-settings').show();
                } else {
                    $('#registration-form-settings').hide();
                }

                // 初始化时检查手签板状态
                if ($('#c-enable_signature_pad').val() == '1') {
                    $('#signature-pad-settings').show();
                } else {
                    $('#signature-pad-settings').hide();
                }

                // 初始化时检查事项设置状态
                if ($('#c-enable_matters_setting').val() == '1') {
                    $('#matters-settings').show();
                } else {
                    $('#matters-settings').hide();
                }

                // 初始化时检查线下报名状态
                if ($('#c-enable_offline_registration').val() == '1') {
                    $('#offline-registration-settings').show();
                } else {
                    $('#offline-registration-settings').hide();
                }

                // 初始化时检查报名条件状态
                if ($('#c-enable_registration_conditions').val() == '1') {
                    $('#registration-conditions-settings').show();
                } else {
                    $('#registration-conditions-settings').hide();
                }

                // 初始化时检查报名须知状态
                if ($('#c-enable_terms_agreement').val() == '1') {
                    $('#terms-agreement-settings').show();
                } else {
                    $('#terms-agreement-settings').hide();
                }

                // 添加switcher事件绑定
                $(document).on('click', '[data-toggle="switcher"]', function (e) {
                    e.preventDefault();
                    var $this = $(this);
                    var inputId = $this.data('input-id');
                    var yesValue = $this.data('yes') || '1';
                    var noValue = $this.data('no') || '0';
                    var $input = $('#' + inputId);
                    var $icon = $this.find('i');

                    // 获取当前值
                    var currentValue = $input.val();

                    // 切换值
                    var newValue = (currentValue == yesValue) ? noValue : yesValue;
                    $input.val(newValue);

                    // 更新图标和样式
                    if (newValue == yesValue) {
                        // 激活状态
                        $icon.removeClass('fa-toggle-off fa-flip-horizontal text-muted')
                            .addClass('fa-toggle-on text-success');
                        $this.removeClass('text-muted').addClass('text-success');
                    } else {
                        // 非激活状态
                        $icon.removeClass('fa-toggle-on text-success')
                            .addClass('fa-toggle-off fa-flip-horizontal text-muted');
                        $this.removeClass('text-success').addClass('text-muted');
                    }

                    // 触发change事件
                    $input.trigger('change');

                    // 特殊处理分阶段报名switcher
                    if (inputId === 'c-is_staged') {
                        if (newValue == '1') {
                            $('#staged-names').show();
                            $('#staged-registration-info').show();
                        } else {
                            $('#staged-names').hide();
                            $('#staged-registration-info').hide();
                            // 清空相关字段
                            $('#c-staged_name').val('');
                            $('#staged-registration-info input, #staged-registration-info select').val('');
                        }
                    }

                    // 特殊处理报名数量限制switcher
                    if (inputId === 'c-enable_quantity_limit') {
                        if (newValue == '1') {
                            $('#quantity-limit-settings').show();
                        } else {
                            $('#quantity-limit-settings').hide();
                            // 清空相关字段
                            $('#quantity-limit-settings input').val('');
                        }
                    }

                    // 特殊处理报名表开启switcher
                    if (inputId === 'c-enable_registration_form') {
                        if (newValue == '1') {
                            $('#registration-form-settings').show();
                        } else {
                            $('#registration-form-settings').hide();
                            // 清空相关字段
                            $('#registration-form-settings input, #registration-form-settings textarea').val('');
                            $('#registration-form-settings input[type="checkbox"]').prop('checked', false);
                        }
                    }

                    // 特殊处理手签板switcher
                    if (inputId === 'c-enable_signature_pad') {
                        if (newValue == '1') {
                            $('#signature-pad-settings').show();
                        } else {
                            $('#signature-pad-settings').hide();
                            // 清空相关字段
                            $('#signature-pad-settings input, #signature-pad-settings select').val('');
                        }
                    }

                    // 特殊处理事项设置switcher
                    if (inputId === 'c-enable_matters_setting') {
                        if (newValue == '1') {
                            $('#matters-settings').show();
                        } else {
                            $('#matters-settings').hide();
                            // 清空相关字段
                            $('#matters-settings input, #matters-settings textarea, #matters-settings select').val('');
                        }
                    }

                    // 特殊处理线下报名switcher
                    if (inputId === 'c-enable_offline_registration') {
                        if (newValue == '1') {
                            $('#offline-registration-settings').show();
                        } else {
                            $('#offline-registration-settings').hide();
                            // 清空相关字段
                            $('#offline-registration-settings input').val('');
                        }
                    }

                    // 特殊处理报名条件switcher
                    if (inputId === 'c-enable_registration_conditions') {
                        if (newValue == '1') {
                            $('#registration-conditions-settings').show();
                        } else {
                            $('#registration-conditions-settings').hide();
                            // 清空相关字段
                            $('#registration-conditions-settings input, #registration-conditions-settings textarea').val('');
                        }
                    }

                    // 特殊处理报名须知switcher
                    if (inputId === 'c-enable_terms_agreement') {
                        if (newValue == '1') {
                            $('#terms-agreement-settings').show();
                        } else {
                            $('#terms-agreement-settings').hide();
                            // 清空相关字段
                            $('#terms-agreement-settings input, #terms-agreement-settings textarea').val('');
                        }
                    }
                });

                // 初始化switcher状态
                $('[data-toggle="switcher"]').each(function () {
                    var $this = $(this);
                    var inputId = $this.data('input-id');
                    var yesValue = $this.data('yes') || '1';
                    var $input = $('#' + inputId);
                    var $icon = $this.find('i');

                    if ($input.length > 0) {
                        var currentValue = $input.val();

                        if (currentValue == yesValue) {
                            // 激活状态
                            $icon.removeClass('fa-toggle-off fa-flip-horizontal text-muted')
                                .addClass('fa-toggle-on text-success');
                            $this.removeClass('text-muted').addClass('text-success');
                        } else {
                            // 非激活状态
                            $icon.removeClass('fa-toggle-on text-success')
                                .addClass('fa-toggle-off fa-flip-horizontal text-muted');
                            $this.removeClass('text-success').addClass('text-muted');
                        }
                    }
                });
            });

            // 添加选项卡切换事件监听器
            $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
                var target = $(e.target).attr('href');
                if (target === '#student-detail' || target === '#registration-info') {
                    loadStudentList(target);
                }
            });

            // 确保页面加载时也检查是否需要加载数据
            var activeTab = $('#student-detail').hasClass('active') ? '#student-detail' :
                $('#registration-info').hasClass('active') ? '#registration-info' : null;
            if (activeTab) {
                loadStudentList(activeTab);
            }

            // 性别转换函数
            function getGenderText(gender) {
                if (gender === '男') return '男';
                if (gender === '女') return '女';
                if (gender === 1 || gender === '1') return '男';
                if (gender === 2 || gender === '2') return '女';
                return '-';
            }

            // 加载报名学员列表
            function loadStudentList(target) {
                var applyId = row.id;
                var $list = target === '#student-detail' ? $('#student-list') : $('#registration-list');

                // 如果已经加载过数据，则不再重复加载
                if ($list.data('loaded')) {
                    return;
                }

                // 根据选项卡类型设置列数
                var colspan = target === '#student-detail' ? 10 : 8;
                $list.html('<tr><td colspan="' + colspan + '" class="text-center">加载中...</td></tr>');

                // 确保applyId存在
                if (!applyId) {
                    $list.html('<tr><td colspan="' + colspan + '" class="text-center">未找到报名ID</td></tr>');
                    return;
                }

                $.get('applyform/apply/studentList', { apply_id: applyId }, function (response) {
                    if (response.code === 1) {
                        var data = response.data.list;
                        $list.empty();

                        if (data.length === 0) {
                            $list.html('<tr><td colspan="' + colspan + '" class="text-center">暂无数据</td></tr>');
                            return;
                        }

                        $.each(data, function (index, item) {
                            var row = target === '#student-detail' ?
                                $('<tr>' +
                                    '<td>' + (index + 1) + '</td>' +
                                    '<td>' + item.username + '</td>' +
                                    '<td>' + item.mobile + '</td>' +
                                    '<td>' + item.gender + '</td>' +
                                    '<td>' + item.course_name + '</td>' +
                                    '<td>' + item.create_time + '</td>' +
                                    '<td>' + item.amount + '</td>' +
                                    '<td>' + (item.payment_status === 1 ? '已缴费' : '未缴费') + '</td>' +
                                    '<td>' + (item.pay_time || '-') + '</td>' +
                                    '<td>' + (item.order_sn || '-') + '</td>' +
                                    '</tr>') :
                                $('<tr>' +
                                    '<td>' + (index + 1) + '</td>' +
                                    '<td>' + item.username + '</td>' +
                                    '<td>' + item.course_name + '</td>' +
                                    '<td>' + item.create_time + '</td>' +
                                    '<td>' + item.amount + '</td>' +
                                    '<td>' + (item.payment_status === 1 ? '已缴费' : '未缴费') + '</td>' +
                                    '<td>' + (item.pay_time || '-') + '</td>' +
                                    '<td>' + (item.order_sn || '-') + '</td>' +
                                    '</tr>');
                            $list.append(row);
                        });
                        $list.data('loaded', true);
                    } else {
                        alert(response.msg);
                        $list.html('<tr><td colspan="' + colspan + '" class="text-center">' + response.msg + '</td></tr>');
                    }
                }).fail(function (xhr, status, error) {
                    alert('加载失败，请重试');
                    $list.html('<tr><td colspan="' + colspan + '" class="text-center">加载失败，请重试</td></tr>');
                });
            }

            $("#edit-form2").click(function () {
                // 提取所需信息
                const itemName = document.querySelector('#c-title') ? document.querySelector('#c-title').value : '';
                // 由于 edit.html 中没有 c-id 元素，这里移除获取 itemId 的代码
                // const itemId = document.querySelector('#c-id').value;
                const description = document.querySelector('#c-intro') ? document.querySelector('#c-intro').value : '';
                const preStartTime = document.querySelector('#c-start_time') ? document.querySelector('#c-start_time').value : '';
                const preEndTime = document.querySelector('#c-end_time') ? document.querySelector('#c-end_time').value : '';
                const preRegistrationLimit = document.querySelector('#c-max_num') ? document.querySelector('#c-max_num').value : '';

                // 显示信息
                document.getElementById('item-name-display').textContent = itemName;
                // 移除 itemId 显示部分
                // document.getElementById('item-id-display').textContent = itemId;
                $('#description-display').html(description);
                document.getElementById('pre-start-time-display').textContent = preStartTime;
                document.getElementById('pre-end-time-display').textContent = preEndTime;
                document.getElementById('pre-registration-limit-display').textContent = preRegistrationLimit;

                const apiUrl = '/ysapi/v1/EventDetails/EventDetails';

                fetch(apiUrl)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('网络响应不正常');
                        }
                        return response.json();
                    })
                    .then(data => {
                        const vocalClasses = data.data;
                        const classList = document.getElementById('class-list');

                        vocalClasses.forEach(vocalClass => {

                            const classDiv = document.createElement('div');
                            classDiv.classList.add('class-info');

                            const title = document.createElement('h2');
                            title.textContent = `${vocalClass.className}`;
                            classDiv.appendChild(title);

                            const description = document.createElement('p');
                            description.textContent = '说明：暂无详细说明';
                            classDiv.appendChild(description);

                            const startDate = document.createElement('p');
                            startDate.textContent = `报名开始时间：${vocalClass.start_date}`;
                            classDiv.appendChild(startDate);

                            const endDate = document.createElement('p');
                            endDate.textContent = '报名结束时间：暂无信息';
                            classDiv.appendChild(endDate);

                            const ocationName = document.createElement('p');
                            ocationName.textContent = `教学点：${vocalClass.ocation_name}`;
                            classDiv.appendChild(ocationName);

                            const subject = document.createElement('p');
                            subject.textContent = `课程类型：${vocalClass.subjectlv_id_b}`;
                            classDiv.appendChild(subject);

                            const registrationStatus = document.createElement('p');
                            registrationStatus.innerHTML = '预报名情况》：暂无信息<p><p>';
                            classDiv.appendChild(registrationStatus);

                            classList.appendChild(classDiv);
                        });
                    })
                    .catch(error => {
                    });
            });

            // 监听课堂类型切换
            $(document).on('change', 'input[name="row[table_type]"]', function () {
                updateTableSelectVisibility();
            });

            // 页面初始化时设置显示状态
            $(function () {
                if ($('input[name="row[table_type]"]').length > 0) {
                    // 若未选中，默认选学校=1
                    if ($('input[name="row[table_type]"]:checked').length === 0) {
                        $('input[name="row[table_type]"][value="1"]').prop('checked', true);
                    }
                    updateTableSelectVisibility();
                }
            });


            // 自动扩展窗口大小到100%
            var resize = function () {
                var h = $(window).height();
                $(".panel-body").css("height", h - 100);
            };
            $(window).resize(function () {
                resize();
            });
            resize();

            // 根据课堂类型切换课程表下拉框显示
            function updateTableSelectVisibility() {
                var typeVal = $('input[name="row[table_type]"]:checked').val();
                var t1 = (typeVal === '1');
                var t2 = (typeVal === '2');
                if ($('#c-table_id').length > 0) {
                    $('#c-table_id').closest('div').find('#c-table_id').toggle(t1);
                }
                if ($('#c-publicwelfare_id').length > 0) {
                    $('#c-publicwelfare_id').closest('div').find('#c-publicwelfare_id').toggle(t2);
                }
                // 触发数据加载
                if (t1 && $('#c-table_id').length > 0) {
                    $('#c-table_id').trigger('change2');
                }
                if (t2 && $('#c-publicwelfare_id').length > 0) {
                    $('#c-publicwelfare_id').trigger('change2');
                }
            }

            // 监听课堂类型切换
            $(document).on('change', 'input[name="row[table_type]"]', function () {
                updateTableSelectVisibility();
            });
            $(document).one('change', '#c-special_channel_scope', function () {
                $('#c-classes_id').trigger('change2');
            });
            // 页面初始化时设置显示状态
            $(function () {
                if ($('input[name="row[table_type]"]').length > 0) {
                    // 若未选中，默认选学校=1
                    if ($('input[name="row[table_type]"]:checked').length === 0) {
                        $('input[name="row[table_type]"][value="1"]').prop('checked', true);
                    }
                    updateTableSelectVisibility();
                }
            });
            if (!document.querySelector('script[src="/assets/js/backend/common/add.js"]')) {
                var script = document.createElement('script');
                script.src = '/assets/js/backend/common/add.js';
                document.head.appendChild(script);
            }
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));

                // 监听课程表项目名称的change事件
                $(document).on('change', '#c-table_id', function () {
                    var selectedText = $(this).find('option:selected').text().trim();

                    // 如果选中了有效的课程表项目（不是"请选择"等提示文本）
                    if (selectedText && selectedText !== '' && selectedText !== '请选择课程表' && selectedText !== '请选择') {
                        // 去掉"课程表"三个字
                        var projectName = selectedText.replace(/课程表/g, '');

                        // 如果报名项目名称为空，则自动填充
                        var $title = $('#c-title');
                        if ($title.length > 0 && (!$title.val() || $title.val().trim() === '')) {
                            $title.val(projectName);
                        }

                        // 如果报名表标题为空，则自动填充
                        var $formTitle = $('input[name="row[form_title]"]');
                        if ($formTitle.length > 0 && (!$formTitle.val() || $formTitle.val().trim() === '')) {
                            $formTitle.val(projectName);
                        }
                    }
                });
            },
            formatter: {//渲染的方法
                url: function (value, row, index) {
                    return '<div class="input-group input-group-sm" style="width:250px;"><input type="text" class="form-control input-sm" value="' + value + '"><span class="input-group-btn input-group-sm"><a href="' + value + '" target="_blank" class="btn btn-default btn-sm"><i class="fa fa-link"></i></a></span></div>';
                },
                ip: function (value, row, index) {
                    return '<a class="btn btn-xs btn-ip bg-success"><i class="fa fa-map-marker"></i> ' + value + '</a>';
                },
                status: function (value, row, index) {
                    //添加上btn-change可以自定义请求的URL进行数据处理
                    return '<a class="btn-change text-success" data-url="applyform/apply/status" data-confirm="确认切换状态？" data-id="' + row.id + '"><i class="fa ' + (row.status == 0 || row.status == null ? 'fa-toggle-on fa-flip-horizontal text-gray' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
                changeStatus: function (value, row, index) {
                    //添加上btn-change可以自定义请求的URL进行数据处理
                    return '<a class="btn-change text-success" data-url="applyform/apply/applyform/apply/changeStatus" data-confirm="确认切换状态？" data-id="' + row.id + '"><i class="fa ' + (row.status === 0 ? 'fa-toggle-on fa-flip-horizontal text-gray' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
            },
            events: {//绑定事件的方法
                ip: {
                    //格式为：方法名+空格+DOM元素
                    'click .btn-ip': function (e, value, row, index) {
                        e.stopPropagation();
                        var container = $("#table").data("bootstrap.table").$container;
                        var options = $("#table").bootstrapTable('getOptions');
                        //这里我们手动将数据填充到表单然后提交
                        $("form.form-commonsearch [name='ip']", container).val(value);
                        $("form.form-commonsearch", container).trigger('submit');
                        Toastr.info("执行了自定义搜索操作");
                    }
                },
            }
        }
    };
    return Controller;
});
